//
//  FoodOrderVC.swift
//  SlaughterClient
//
//  Created by 邱仙凯 on 2021/9/13.
//  Copyright © 2021 zwb. All rights reserved.
//

import UIKit
import SVProgressHUD
import EmptyDataSet_Swift



class ZyaFoodOrderVC: UIViewController,UISearchBarDelegate,UITableViewDelegate,UITableViewDataSource,EmptyDataSetSource,EmptyDataSetDelegate {
    
 
    
    var page = 1
    
    var titleStr = ZTBInnerType.zbListKHW
    var dataArray = [ZyaFoodOrderModel]()
    var z_zb_id = "" // 出价记录使用
    
    var listType = TBandJPType.TB
    var btnflag = "1"
    var keyword = ""
    var minMoney = ""
    var maxMoney = ""
    var startDate = ""
    var endDate = ""
    var s_status = ""
    
    //CollectionView
    let sourceTypeArr = ["全部","采购合同类","药品疫苗类","耗用品类","试剂耗材类","环保药剂类","办公用品类","设备类","燃料类","其他类"]
    let statusArr = ["全部","在途","已签收"]
    let dateArr = ["全部","3日内","7日内","1月内","3月内"]
    
    
    let bigArr = ["类型","状态","时间","地区"]
    let source3_1 = ["物虽小","勿私藏","苟私藏","亲心伤"]
    let source3_2 = ["亲所好","力为具","亲所恶"]
    
    var followTag = ""
     let helper = ZyaTenderHelper()
    private var searchBar:UISearchBar?
    
    lazy var tableView:UITableView = {
        let v = UITableView(frame: self.view.bounds)
        v.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 100, right: 0)
        v.delegate = self
        v.dataSource = self
        v.emptyDataSetSource = self
        v.emptyDataSetDelegate = self
        return v
    }()
   
    lazy var bV:UIView = {
        let v = UIView(frame: CGRect(x: 0, y: 0, width: KSGlobal.screenW, height: 40))
        return v
    }()
    lazy var filterV:KSRaiseUpFilterV = {
        let v = KSRaiseUpFilterV(startY:0, arr: [SlideContent(type: .dateRegion, title: "日期",startDate: startDate,endDate: endDate),SlideContent(type: .multiSelect, title: "状态",dataArr: ["未提交","已提交","已下单","已完成"].map{ SeString(title: $0, ks_selected: false) },numberOfRow: 5,open: true),
            SlideContent(type: .moneyRegion, title: "金额")])
        return v
     
    }()
    
   
    
    init() {
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
   
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "食品订单"
        self.view.addSubview(tableView)
         self.configSearch()
        bV.addSubview(searchBar!)
         tableView.tableHeaderView = bV
        helper.callTableRefreshClosure = {
            self.tableView.mj_header?.beginRefreshing()
            
        }
        navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(named: "guolv"), style: .plain, target: self, action: #selector(rightAction))
        tableView.rowHeight = 136
        tableView.separatorStyle = .none
        tableView.mj_header = KSRefreshHeader { [unowned self] in
            self.page = 1
            self.network()
        }
        tableView.mj_footer = ZyaFoodORefreshFooter { [unowned self] in
            self.page += 1
            self.network()
        }
        tableView.mj_header?.beginRefreshing()
        
        tableView.register(ZyaFoodOrderCell.self, forCellReuseIdentifier: ZyaFoodOrderCell.identifier)
    
        
        let btn = UIButton()
        btn.setTitle("新增", for: .normal)
        btn.layer.masksToBounds = true
        btn.layer.cornerRadius = 20
        btn.backgroundColor = Theme.primaryColor()
         btn.addTouchUpInSideAction { _ in
            let vc = ZyaFoodOrderFormVC()
            vc.refreshClosure = {
                self.tableView.mj_header?.beginRefreshing()
            }
            self.navigationController?.pushViewController(vc, animated: true)
            
        } 
        let bottmV = UIView()
        bottmV.backgroundColor = UIColor(kshex:"#f1f1f1")
        self.view.addSubview(bottmV)
        bottmV.addSubview(btn)
        
        bottmV.snp.makeConstraints { make in
            make.bottom.left.right.equalTo(self.view)
             make.height.equalTo(60)
        }
        btn.snp.makeConstraints { make in
            make.centerY.equalTo(bottmV)
            make.centerX.equalTo(bottmV)
            make.width.equalTo(KSGlobal.screenW - 40)
            make.height.equalTo(40)
        }
       
        
        tableView.tableFooterView = UIView()
        tableView.backgroundColor = UIColor(kshex:"#f1f1f1")
        self.configFilterV()
      
    }
    func configFilterV() {
        self.filterV.confirmClosure = { arr in
            self.startDate = arr[0].startDate
            self.endDate = arr[0].endDate
            
            let ss = arr[1].dataArr!.filter{ $0.ks_selected }.compactMap { ZyaFoodOStatusDicDesc[$0.title] }
            self.s_status = ss.joined(separator: ",")
          
            self.minMoney = arr[2].minMoney
            self.maxMoney = arr[2].maxMoney
            
             self.filterV.close()
            self.tableView.mj_header?.beginRefreshing()
        }
    
    }
    
    @objc func rightAction() {
//        self.filterV.present()
        self.filterV.present()
     }

    
    func configSearch () {
        
        searchBar = TenderSearchBar(frame:CGRect(x:0,y:3,width:KSGlobal.screenW,height:40))
        if #available(iOS 13.0, *) {
            searchBar!.searchTextField.backgroundColor = .white
            searchBar!.searchTextField.layer.cornerRadius = 18
            searchBar!.searchTextField.layer.masksToBounds = true
        } else {
            // Fallback on earlier versions
            let searchField = searchBar!.value(forKey: "searchField") as! UITextField
            searchField.backgroundColor = .white
            searchField.layer.cornerRadius = 18
            searchField.layer.masksToBounds = true
            
        }
        searchBar?.barTintColor = UIColor(kshex: "#f5f5f5")
        searchBar?.backgroundImage = UIImage()
        
        let toolbar = UIToolbar()
        toolbar.barStyle = UIBarStyle.default
        toolbar.sizeToFit()
        let buttonflexible = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.flexibleSpace, target: nil, action: nil)
        let buttonDone = UIBarButtonItem(title: "完成", style: UIBarButtonItem.Style.done, target: self, action: #selector(doneClickss))
        buttonDone.tintColor = UIColor.black
        toolbar.setItems([buttonflexible, buttonDone], animated: true)
        
        searchBar!.inputAccessoryView = toolbar
        
        
        
        searchBar!.text = self.keyword
        searchBar!.placeholder = "请输入客户名称或订单号搜索"
        searchBar!.delegate = self
        
        
    }
    
    @objc func doneClickss() {
        self.searchBar!.resignFirstResponder()
    }
    
   
    @objc func mapAction() {
        
    }
    
    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        searchBar.resignFirstResponder()
        self.keyword = searchBar.text.unwrap
        self.tableView.mj_header?.beginRefreshing()
    }
    
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return self.dataArray.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        
        guard let cell = tableView.dequeueReusableCell(withIdentifier: ZyaFoodOrderCell.identifier, for: indexPath) as? ZyaFoodOrderCell else {
            fatalError("cell error")
        }
        
        let one = self.dataArray[indexPath.row]
        cell.one = one
 
       
        cell.ob.clickAction = { [one] tag,title  in
            if title == "提交" {
                alertUtil(self, title: "确认提交？", operateS: [nameAction(name: "确定", action: { (_) in
                    KSNetwork.shared.doRequest(API.pFoodRefer(id_key: self.dataArray[indexPath.row].idKey.unwrap)) { (data:BaseResult<OperateResult>) in
                        if data.flag == TRUE {
                            self.tableView.mj_header?.beginRefreshing()
                        } else {
                            KSToast(data.message.unwrap)
                        }
                    }
                })])
 
            }
            if title == "反提交" {
                alertUtil(self, title: "确认反提交？", operateS: [nameAction(name: "确定", action: { (_) in
                    KSNetwork.shared.doRequest(API.pFoodUnRefer(id_key: self.dataArray[indexPath.row].idKey.unwrap)) { (data:BaseResult<OperateResult>) in
                        if data.flag == TRUE {
                            self.tableView.mj_header?.beginRefreshing()
                        } else {
                            KSToast(data.message.unwrap)
                        }
                    }
                })])
 
            }
        
            if title == "再来一单" {
                let vc = ZyaFoodOrderFormVC()
                vc.model = one
                vc.excuteType = .copy
                vc.refreshClosure = {
                    self.tableView.mj_header?.beginRefreshing()
                }
                self.navigationController?.pushViewController(vc, animated: true)
            }
            if title == "删除" {
                alertUtil(self, title: "确认删除？", operateS: [nameAction(name: "确定", action: { (_) in
                    KSNetwork.shared.doRequest(API.pFoodDelete(id_key: self.dataArray[indexPath.row].idKey.unwrap)) { (data:BaseResult<OperateResult>) in
                        if data.flag == TRUE {
                            self.tableView.mj_header?.beginRefreshing()
                        } else {
                            KSToast(data.message.unwrap)
                        }
                    }
                })])
            }
        }
        
        return cell
        
        
        
    }
    
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        let one = self.dataArray[indexPath.row]
        
        let vc = ZyaFoodOrderFormVC()
        vc.model = one
         if one.sAuditMark == "1" || one.sAuditMark == "3" || one.sAuditMark == "9" {
            vc.excuteType = .view
        } else {
            vc.excuteType = .fix
        }
        vc.refreshClosure = {
            self.tableView.mj_header?.beginRefreshing()
        }
        self.navigationController?.pushViewController(vc, animated: true)
        
    }
    func network () {
 
        let api = API.pFoodQueryOrder(page: "\(self.page)", size: "\(KSGlobal.pageSize)", s_begin_dt: startDate, s_end_dt: endDate, s_money_min: self.minMoney, s_money_max: self.maxMoney, s_title: self.keyword, s_city: "", s_status: s_status)
        
        KSNetwork.shared.doRequest(api,showHud: false) { [weak self] (data:BaseResult<ZyaFoodOrderModel>) in
            guard let `self` = self else { return }
            if data.flag == TRUE {
                if let infos = data.infos {
                    if self.page == 1 {
                        self.dataArray.removeAll()
                    }
                    self.dataArray += infos
                    self.tableView.reloadData()
                    self.tableView.mj_header?.endRefreshing()
                    if infos.count < 10 {
                        self.tableView.mj_footer?.endRefreshingWithNoMoreData()
                    } else {
                        self.tableView.mj_footer?.endRefreshing()
                    }
                }
            } else {
                KSToast(data.message)
            }
        }
    }
     
    
    
    
    func customView(forEmptyDataSet scrollView: UIScrollView) -> UIView? {
        let v = UIImageView(image: UIImage(named: "zanwushuju"))
        v.frame = CGRect(x: 0, y: 0, width: 120, height: 100)
        return v
    }
    func emptyDataSetShouldAllowTouch(_ scrollView: UIScrollView) -> Bool {
        return true
    }
    func emptyDataSetShouldAllowScroll(_ scrollView: UIScrollView) -> Bool {
        return true
    }
    
    deinit {
        print("销毁")
    }
}

 
class ZyaFoodORefreshFooter: KSRefreshFooter {
    override func prepare() {
        super.prepare()
         self.setTitle("", for: .noMoreData)
    }

}
